package com.spring.context.bean;

public class DefaultBeanFactory {

    private BeanDefinitionRegister DEFINITIONS = new BeanDefinitionRegister();

    private final SingletonBeanRegister SINGLETONS = new SingletonBeanRegister();

    public Object getBean(String beanName) {
        if (!DEFINITIONS.containsBeanDefinition(beanName)) {
            throw new RuntimeException("No " + beanName + "defined!");
        }

        BeanDefinition db = DEFINITIONS.getBeanDefinition(beanName);

        if (db.getScope() == BeanDefinition.SCOPE_SINGLETON) {
            if (SINGLETONS.containsSingleton(beanName)) {
                return SINGLETONS.getSingleton(beanName);
            }
            SINGLETONS.registerSingleton(beanName, createBean(db));
            return SINGLETONS.getSingleton(beanName);
        }
        if (db.getScope() == BeanDefinition.SCOPE_PROTOTYPE) {
            return createBean(db);
        }
        return null;
    }

    public Object createBean(BeanDefinition db) {
        Class clazz = db.getClass();
        
        try {
            return clazz.newInstance();
        }
        catch (InstantiationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }
}
